const fs = require('fs')
const mime = require('mime')
const AWS = require('aws-sdk')
const log = require('../log')
const packageJson = require('../package.json')

const UPLOAD = {}

// 上传
UPLOAD.upload = async(file, options, fileName) => {
  try {
    AWS.config.update(options)
    const S3 = await new AWS.S3()
    const result = await new Promise((resolve, reject) => {
      S3.upload({
          ...options,
          Body: fs.createReadStream(file.path),
          Key: fileName,
          ContentType: mime.getType(file.path)
        },
        (err, data) => {
        if (err == null) {
          log.green(`Upload Success ${data.Location}`)
          resolve(null)
        } else {
          reject(err)
        }
      })
    })
  } catch (err) {
    log.red(`${packageJson.name} Upload Error ${options.prefix}/${fileName}`)
    console.error(err)
  }
}

module.exports = UPLOAD
